from PySide6 import QtWidgets, QtGui
from PySide6.QtCore import Qt, QTimer
import PySide6.QtGui

# 创建画布
class Canvas(QtWidgets.QLabel):
    def __init__(self):
        super().__init__()
        # 画板
        self.canvas = QtGui.QPixmap(self.size().width(), self.size().height())
        # 底色
        self.canvas.fill(Qt.white)
        # 画笔跟踪
        self.last_x, self.last_y = None, None

        # 设置计时器
        self.timer = QTimer()
        # 设置超时事件
        self.timer.timeout.connect(self.timeOut)

    def timeOut(self):
        if self.parentWidget():
            self.parentWidget().onPredictButtonClicked()
        # 停止

    def paintEvent(self, event) -> None:
        with QtGui.QPainter(self) as painter:
            painter.drawPixmap(0, 0, self.canvas)

        return super().paintEvent(event)

    def resizeEvent(self, event) -> None:
        self.canvas = self.canvas.scaled(event.size().width(), event.size().height())

        return super().resizeEvent(event)

    def mouseMoveEvent(self, event):
        # 开始计时
        self.timer.start(1500)

        if self.last_x is None:
            self.last_x = event.x()
            self.last_y = event.y()
            return

        painter = QtGui.QPainter(self.canvas)

        p = painter.pen()
        # 笔宽度
        p.setWidth(20)
        p.setCapStyle(Qt.RoundCap)
        p.setJoinStyle(Qt.RoundJoin)

        painter.setPen(p)
        painter.drawLine(self.last_x, self.last_y, event.x(), event.y())
        painter.end()

        # 储存本次拿到的鼠标坐标，供下一帧使用
        self.last_x = event.x()
        self.last_y = event.y()

        self.update()
        return super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        self.last_x, self.last_y = None, None

        return super().mouseReleaseEvent(event)

    def clear(self):
        # 清空
        self.canvas.fill(Qt.white)

        self.update()

    def getImage(self):
        # 把canvas的内容转换成QImage
        return self.canvas.toImage()